package dao

import (
	"encoding/json"
	"errors"
	"fmt"
	"go.uber.org/zap"
	"homepage_srv/homepage"
	"homepage_srv/model"
	"log"
	"math/rand"
	"smart-health-platforms/config"
	"smart-health-platforms/pkg"
)

// 同步商品库存到redis
func SyncGoodsStatus(goodsId, sdkId, stock int) {
	key := fmt.Sprintf("goods_stock:%d:%d", goodsId, sdkId)
	for i := 1; i < stock+1; i++ {
		config.Rdb.LPush(config.Ctx, key, i)
	}
}

// 获取商品库存
func GetGoodsStatus(goodsId, sdkId int) (status int64, err error) {
	key := fmt.Sprintf("goods_stock:%d:%d", goodsId, sdkId)
	return config.Rdb.LLen(config.Ctx, key).Result()
}

// 扣减库存
func DelGoodsStock(goodsId, sdkId, status int) {
	key := fmt.Sprintf("goods_stock:%d:%d", goodsId, sdkId)
	for i := 0; i < status; i++ {
		config.Rdb.LPop(config.Ctx, key)
	}
}

// 商品添加
func GoodCreate(in *homepage.GoodCreateRequest) (goodId int64, err error) {
	good := model.Good{
		BrandId:       uint32(uint(in.BrandId)),
		MainImage:     in.MainImage,
		SliderImageId: uint32(uint(in.SliderImageId)),
		StoreName:     in.StoreName,
		StoreInfo:     in.StoreInfo,
		CateId:        uint32(uint(in.CateId)),
	}
	//添加商品
	if err = good.Create(); err != nil {
		return 0, errors.New("添加商品失败")
	}

	return int64(good.Id), nil
}

// 商品SDK添加
func GoodCreateSKU(in *homepage.GoodCreateSKURequest) (id int64, err error) {
	goodSKU := model.GoodSku{
		GoodId: uint32(in.GoodId),
		Color:  in.Color,
		Stock:  uint32(in.Stock),
		Sales:  uint32(in.Sales),
		Price:  float64(in.Price),
		Image:  in.Image,
		Weight: float64(in.Weight),
		Volume: float64(in.Volume),
	}
	//添加商品SDK
	if err = goodSKU.Create(); err != nil {
		return 0, errors.New("添加商品SDK失败")
	}
	//同步商品库存到redis
	SyncGoodsStatus(int(in.GoodId), int(goodSKU.Id), int(in.Stock))
	return int64(goodSKU.Id), nil
}

// 商品详情
func GetGoodDetail(in *homepage.GoodDetailRequest) (*model.Good, error) {
	var good model.Good
	good.Id = in.Id
	if err := good.Detail(); err != nil {
		pkg.Warn("商品详情查询失败")
		return nil, err
	}
	//商品热度自动+1
	if err := good.GoodHot(); err != nil {
		pkg.Warn("商品热度增加失败")
		return nil, err
	}
	//将查询到的数据存入redis
	jsonData, _ := json.Marshal(&good)
	config.Rdb.Set(config.Ctx, "goodDatil", jsonData, 0)
	return &good, nil
}

// 商品SDK详情
func GoodDetailSKU(in *homepage.GoodDetailSKURequest) ([]*homepage.GoodSKU, error) {
	var goodSKU model.GoodSku
	goodSKUList, err := goodSKU.GoodSKU(in.GoodId)
	if err != nil {
		pkg.Error("查询商品SKU失败",
			zap.Uint64("good_id", in.GoodId),
			zap.Error(err))
		return nil, fmt.Errorf("查询商品SKU失败: %v", err)
	}
	key := fmt.Sprintf("good_sku: %d", in.GoodId)
	data := config.Rdb.Get(config.Ctx, key).Val()
	if data == "" {
		jsonData, _ := json.Marshal(&goodSKUList)
		config.Rdb.Set(config.Ctx, key, jsonData, 0)
	} else {
		err = json.Unmarshal([]byte(data), &goodSKUList)
		if err != nil {
			pkg.Warn("数据反序列化失败")
			return nil, errors.New("数据反序列化失败")
		}
	}
	var result []*homepage.GoodSKU
	for _, sku := range goodSKUList {
		list := homepage.GoodSKU{
			Id:     sku.Id,
			GoodId: sku.GoodId,
			Color:  sku.Color,
			Stock:  sku.Stock,
			Sales:  sku.Sales,
			Price:  sku.Price,
			Image:  sku.Image,
			Weight: sku.Weight,
			Volume: sku.Volume,
		}
		result = append(result, &list)
	}
	pkg.Warn("商品SKU详情列表展示成功")
	return result, nil
}

// 商品图片详情
func GetGoodAlbums(in *homepage.GoodAlbumsRequest) ([]*homepage.AlbumsList, error) {
	var albums model.GoodAlbums
	albumsList, _ := albums.Albums(int64(in.GoodId))
	key := fmt.Sprintf("good_alums: %d", in.GoodId)
	data := config.Rdb.Get(config.Ctx, key).Val()
	if data == "" {
		jsonData, _ := json.Marshal(&albumsList)
		config.Rdb.Set(config.Ctx, key, jsonData, 0)
	} else {
		err := json.Unmarshal([]byte(data), &albumsList)
		if err != nil {
			pkg.Warn("数据反序列化失败")
			return nil, errors.New("数据反序列化失败")
		}
	}
	var result []*homepage.AlbumsList
	for _, re := range albumsList {
		result = append(result, &homepage.AlbumsList{
			Id:       re.Id,
			GoodId:   re.GoodId,
			ImageUrl: re.ImageUrl,
		})
	}
	pkg.Warn("商品图片列表展示成功")
	return result, nil
}

// 商品搜索
func GoodSearch(StoreName string) []*homepage.GoodSearch {
	//商品表
	var good model.Good
	good.StoreName = StoreName
	//展示商品信息
	listGood, err := good.ListGood(StoreName)
	if err != nil {
		return nil
	}
	var goods []*homepage.GoodSearch
	for _, search := range listGood {
		goods = append(goods, &homepage.GoodSearch{
			Id:               search.Id,
			BrandName:        search.BrandName,
			BrandDescription: search.BrandDescription,
			MainImage:        search.MainImage,
			StoreName:        search.StoreName,
			Sales:            search.Sales,
			StoreInfo:        search.StoreInfo,
		})
	}
	log.Println(listGood)
	//热词搜索表
	var searchLogs model.SearchLogs
	searchLogs.UserId = 1
	searchLogs.SearchTerm = StoreName
	//查询热词搜索表
	if err = searchLogs.List(StoreName); err != nil {
		return nil
	}
	//如果不存在则添加
	if searchLogs.Id == 0 {
		if err = searchLogs.Creat(); err != nil {
			return nil
		}
	}
	//如果表里已经有热词，增加点击量
	if err = searchLogs.IncreaseClickThroughRates(StoreName); err != nil {
		return nil
	}
	return goods
}

// 商品搜索
func HotWordSearch(HouId int64) []*homepage.HotWordSearch {
	var searchLogs model.SearchLogs
	searchLogs.Id = HouId
	if err := searchLogs.ListOneHotSearch(); err != nil {
		return nil
	}

	var good model.Good
	listGood, err := good.ListHotGood(searchLogs.SearchTerm)
	if err != nil {
		return nil
	}
	var goods []*homepage.HotWordSearch
	for _, search := range listGood {
		goods = append(goods, &homepage.HotWordSearch{
			BrandName:        search.BrandName,
			BrandDescription: search.BrandDescription,
			MainImage:        search.MainImage,
			StoreName:        search.StoreName,
			Sales:            search.Sales,
			StoreInfo:        search.StoreInfo,
			Id:               search.Id,
		})
	}
	return goods
}

// 商品热词搜索
func GoodHotSearch() []*homepage.GoodHotSearch {
	//商品表
	var searchLogs model.SearchLogs
	searchLogs.UserId = 1
	search, err := searchLogs.ListHotSearch()
	if err != nil {
		return nil
	}

	var hotSearchs []*homepage.GoodHotSearch

	for _, hotSearch := range search {
		hotSearchs = append(hotSearchs, &homepage.GoodHotSearch{
			Id:         hotSearch.Id,
			SearchTerm: hotSearch.SearchTerm,
		})
	}
	return hotSearchs
}

// 商品列表
func GoodList(CateId int) []*homepage.GoodList {
	var good model.Good
	good.CateId = uint32(CateId)
	//展示商品信息
	listGood, err := good.GoodList(int(good.CateId))
	if err != nil {
		return nil
	}
	var goods []*homepage.GoodList
	for _, search := range listGood {
		goods = append(goods, &homepage.GoodList{
			Id:               search.Id,
			BrandName:        search.BrandName,
			BrandDescription: search.BrandDescription,
			MainImage:        search.MainImage,
			StoreName:        search.StoreName,
			Sales:            search.Sales,
			StoreInfo:        search.StoreInfo,
		})
	}
	return goods
}

// 轮播图
func CarouselList() []*homepage.Carousel {
	var goodAlbums model.GoodAlbums
	albumsList, err := goodAlbums.Carousel()
	if err != nil {
		return nil
	}
	var carouselList []*homepage.Carousel
	for _, item := range albumsList {
		carouselList = append(carouselList, &homepage.Carousel{
			Title:           item.Title,
			ImageUrl:        item.ImageUrl,
			Pattern:         item.Pattern,
			ImgStatus:       item.ImgStatus,
			EventUploadTime: item.EventUploadTime,
		})
	}
	return carouselList
}

// 商品推荐
func GoodRecomment(in *homepage.GoodRecommentRequest) ([]*homepage.Recomment, error) {
	//接受参数
	var good model.Good
	good.CateId = uint32(in.CateId)
	//查询商品信息
	goodList, err := good.GoodRecomment(uint64(in.CateId))
	if err != nil {
		pkg.Error("热度商品信息查询失败: %s", zap.Error(err))
		return nil, errors.New("热度商品信息查询失败")
	}
	//存储查询到的商品信息
	var goodLists []*homepage.Recomment
	for _, recomment := range goodList {
		list := homepage.Recomment{
			Id:               recomment.Id,
			BrandName:        recomment.BrandName,
			BrandDescription: recomment.BrandDescription,
			MainImage:        recomment.MainImage,
			SliderImageId:    recomment.SliderImageId,
			StoreName:        recomment.StoreName,
			Hot:              recomment.Hot,
			Sales:            recomment.Sales,
			StoreInfo:        recomment.StoreInfo,
			CateId:           recomment.CateId,
		}
		goodLists = append(goodLists, &list)
	}
	return goodLists, err
}

// 根据商品查询商品店铺信息
func GoodShop(in *homepage.GoodShopRequest) (goodShop *model.Shop, err error) {
	//接收参数
	var good model.Good
	good.Id = uint64(in.GoodId)
	//查询商品id
	goodShop, err = good.GoodShop(uint64(in.GoodId))
	if err != nil {
		pkg.Error("商品信息查询失败: %s", zap.Error(err))
		return nil, errors.New("商品信息查询失败")
	}
	return goodShop, err
}

// 广告弹窗
func AdvertisementPopUpWindow() (m *model.GoodAlbums, err error) {
	var goodAlbums model.GoodAlbums
	albumsList, err := goodAlbums.Advertisement()
	if err != nil {
		return nil, err
	}
	var list []model.GoodAlbums
	for _, v := range albumsList {
		list = append(list, model.GoodAlbums{
			Id:       v.Id,
			Title:    v.Title,
			ImageUrl: v.ImageUrl,
		})
	}
	albums := list[rand.Intn(len(list))]
	return &albums, nil
}
